package com.speedchina.common.download.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IoUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * @author 19435
 */
public class MyUrlImageConverter implements Converter<Object> {

    private final static Integer SUCCESS_CODE = 200;
    @Override
    public Class supportJavaTypeKey() {
        return URL.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.IMAGE;
    }

    @Override
    public Object  convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration) {
        throw new UnsupportedOperationException("Cannot convert images to url.");
    }

    @Override
    public CellData convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException {
        if (value == null) {
            return new CellData(value);
        }
        URL url = new URL(String.valueOf(value));
        InputStream inputStream = null;
        try {
            //开启连接
            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            //获取响应状态
            int statusCode = uc.getResponseCode();
            if (statusCode == SUCCESS_CODE) {
                //图片获取成功返回流 否则不写入
                inputStream =url.openStream();
                byte[] bytes = IoUtils.toByteArray(inputStream);
                return new CellData(bytes);
            }
            return new CellData();
        }catch (Exception exception){
            return new CellData();
        }finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
}
